
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

using com.ReinforceLab.AudioModem;
using com.ReinforceLab.AudioModem.FSK;

namespace ArduinoiPhoneShield
{
	public partial class MainPanel : UIViewController
	{        
        AudioQueueAudioPHY _audioPhy;
        ToneSignalSource _toneSource;        
        NSTimer _timer;

		#region Constructors

		// The IntPtr and initWithCoder constructors are required for controllers that need 
		// to be able to be created from a xib rather than from managed code

		public MainPanel (IntPtr handle) : base(handle)
		{
			Initialize ();            
		}

		[Export("initWithCoder:")]
		public MainPanel (NSCoder coder) : base(coder)
		{
			Initialize ();
		}

		public MainPanel () : base("MainPanel", null)
		{
			Initialize ();
		}

		void Initialize ()
		{
		}		
		#endregion

        public override void LoadView()
        {            
            base.LoadView();
            _soundOutButton.TouchUpInside += new EventHandler(_soundOutButton_TouchUpInside);            
        }
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);
            /*
            _timer = NSTimer.CreateRepeatingTimer(TimeSpan.FromMilliseconds(200), new MonoTouch.Foundation.NSAction(_timerWorker));
            NSRunLoop.Current.AddTimer(_timer, "NSDefaultRunLoopMode");                        
             */
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            int samplingRate = 44100;            
            _audioPhy = new AudioQueueAudioPHY(samplingRate);
            _toneSource = new ToneSignalSource(_audioPhy, 440, short.MaxValue);
            _audioPhy.Start(_toneSource);
        }
        public override void ViewWillDisappear(bool animated)
        {
            /*
            if (null != _timer)
            {
                _timer.Invalidate();
                _timer = null;
            } */           
            base.ViewWillDisappear(animated);
        }
        void _timerWorker()
        {
            //System.Diagnostics.Debug.WriteLine(_toneSource.SignalLevel.ToString());
            //_levelTextLabel.Text = _toneSource.SignalLevel.ToString();
        }
        void _soundOutButton_TouchUpInside(object sender, EventArgs e)
        {
            /*
            for(int i = 0; i < 1; i++)
                _audioPhy.Write(0xA5);
             
            if (_audioPhy.IsRunning)
            {                
                System.Diagnostics.Debug.WriteLine("tone stop");
            }
            else
            {                
                System.Diagnostics.Debug.WriteLine("tone start");
            }* */
        }
	}
}
